package com.kejizhentan.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kejizhentan.cmn.listener.DictListener;
import com.kejizhentan.cmn.service.DictService;
import com.kejizhentan.cmn.mapper.DictMapper;
import com.kejizhentan.yygh.model.cmn.Dict;
import com.kejizhentan.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Service
 public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService{
    /**
     * @Auther: kejizhentan
     * @Date 2022/11/27 16:32
     * @Description: 根据数据id查询子数据列表
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict:dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }
    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Long count = baseMapper.selectCount(wrapper);
        // 0>0    1>0
        return count>0;
    }

    /**
     * @Auther: kejizhentan
     * @Date 2022/11/27 12:24
     * @Description: 数据字典导出
     */
    @Override
    public void exportDict(HttpServletResponse response) throws Exception {
        // 设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里 URLEncoder.encode 可以防止中文乱码,和 EasyExcel 没有关系
        //String fileName = "dict";
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("数据字典", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        // 查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictVoList = new ArrayList<>(dictList.size());
        for (Dict dict : dictList) {
            DictEeVo dictVo = new DictEeVo();
            //dict-->dictvo
            BeanUtils.copyProperties(dict, dictVo);
            dictVoList.add(dictVo);
        }
        try {
            // 调用方法进行写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("dict")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * @Auther: kejizhentan
     * @Date 2022/11/27 13:07
     * @Description: 导入数据字典， allEntries=true方法调用后清空所有缓存
     */
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importDict(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) {
            Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getValue, value));
            return dict.getName();
        } else {
            Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getDictCode, dictCode));
            Long parent_id = dict.getId();
            Dict finalDict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                    .eq(Dict::getParentId, parent_id)
                    .eq(Dict::getValue, value));
            return finalDict.getName();
        }
    }

    // 根据数据id查询子数据列表
    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = baseMapper
                .selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        // 向 dictList 集合中的每个 dict 对象设置 hasChildren
        for (Dict dict : dictList) {
            dict.setHasChildren(this.isChildren(dict.getId()));
        }
        return dictList;
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 根据 dictCode 获取对应 id
        Dict dict = baseMapper.selectOne(new LambdaQueryWrapper<Dict>()
                .eq(Dict::getDictCode, dictCode));
        // 根据 id 获取子节点
        return this.findChildData(dict.getId());
    }
}




